package cn.sylinx.horm.interceptor;

import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * 拦截器管理
 * 
 * @author johnhan
 *
 * @param <T>
 */
public abstract class InterceptorManager<T extends Interceptor> {

    private final Object lock = new Object();
    private T interceptor = null;
    private Class<T> clazz = null;

    public InterceptorManager(Class<T> clazz) {
        this.clazz = clazz;
    }

    public T getInterceptor() {

        if (interceptor != null) {
            return interceptor;
        }

        synchronized (lock) {

            if (interceptor != null) {
                return interceptor;
            }

            // 从配置中获取
            interceptor = getFromConfig();

            // 从ServiceLoader中获取
            if (interceptor == null) {
                interceptor = getFromService();
            }
            // 默认
            if (interceptor == null) {
                interceptor = getDefault();
            }
        }

        return interceptor;
    }

    protected T getFromService() {
        ServiceLoader<T> sl = ServiceLoader.load(clazz);
        Iterator<T> it = sl.iterator();
        if (it.hasNext()) {
            return it.next();
        }
        return null;
    }

    protected abstract T getFromConfig();

    protected abstract T getDefault();

}
